<template>
  <div class="upgrade">
    <img class="logo-img mb-10" src="../../assets/images/updateLogo.svg" />
    <div>
      <el-form 
        label-width="252"
      >
        <el-form-item :label="productName + '序列号：'">
          {{ sysSerialnumber }}
        </el-form-item>
        <el-form-item :label="'当前系统版本号：'">
          {{ sysVersionNumber }}
        </el-form-item>
        <el-form-item :label="'上次更新：'">
          {{ sysLastUpdateTime }}
        </el-form-item>
        <el-form-item :label="'升级包文件：' + uploadFileName">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            action="#"
            :on-change="onSuccess"
            :limit="1"
            :auto-upload="false"
            accept=".rom"
          >
            <el-button class="browse-btn">浏览</el-button>
          </el-upload>
          <el-progress
            v-if="progressPercent < 100 && progressPercent > 0"
            :percentage="progressPercent"
          />
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            :icon="Upload"
            :disabled="uploadFileName == ''"
            class="mt-2"
            @click="dialogAsync = true"
            >开始升级</el-button
          >
        </el-form-item>
      </el-form>
      <!-- <span class="mb-4 inline-block">{{productName}}序列号：{{ sysSerialnumber }}</span>
      <br />
      <span class="mb-4 inline-block">当前系统版本号：{{ sysVersionNumber }}</span>
      <br />
      <span class="mb-4 inline-block">上次更新：{{ sysLastUpdateTime }}</span>
      <br /> -->
    </div>
    <!-- <div class="upload_content mb-4">
      <span>升级包文件：{{ uploadFileName }}</span>
      
    </div> -->

    
    <el-dialog
      :model-value="dialogAsync"
      width="30%"
      :close-on-click-modal="false"
      :center="true"
      :show-close="false"
      @close="closeDialog"
    >
      <template #header>
        <div class="dialog-header" v-if="updateStatus == '升级完成'">
          <el-icon><Select /></el-icon>
          <span class="dialog-title">系统升级成功</span>
        </div>
        <div class="dialog-header" v-else-if="updateStatus == '升级失败'">
          <el-icon><CloseBold /></el-icon>
          <span class="dialog-title">系统升级失败</span>
        </div>
        <div class="dialog-header" v-else>
          <el-icon><WarnTriangleFilled /></el-icon>
          <span class="dialog-title">系统升级确认</span>
        </div>
      </template>
      <div class="config-body">
        <p class="update-tips" v-if="updateStatus == ''">
          请注意，系统升级可能会导致信息丢失。请在执行升级前确保重要信息已经保存备份。<br />
          升级完成后，系统会重新启动，导致所有当前用户退出。
        </p>
        <p class="update-tips" v-else-if="updateStatus == '升级中'">
          系统升级中，请稍等。。。
        </p>
        <p class="update-tips" v-else-if="updateStatus == '升级完成'">
          {{productName}}正在重新启动中。重启后，系统页面会自动刷新。
        </p>
        <p class="update-tips" v-else-if="updateStatus == '升级失败'">
          {{productName}}升级失败，请联系管理员。
        </p>
      </div>
      <template #footer>
        <div class="dialog-footer" v-if="updateStatus == ''">
          <el-button type="primary" :icon="Upload" @click="handleUpdate"
            >升级并重启系统</el-button
          >
          <el-button :icon="Close" @click="closeDialog">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import {
  Upload,
  WarnTriangleFilled,
  Close,
  Select,
  CloseBold,
} from "@element-plus/icons-vue";
import {
  req_getSysLastUpdateTime,
  req_getSysSerialnumber,
  req_systemUpgrade,
  req_getSystemVersionNumber,
  req_getDeviceInfo,
} from "~/utils/axios/index.js";
import { getToken } from "~/utils/storage/cookie.js";
import moment from "moment";
import { useUserStore } from "~/utils/pinia/user.js";
const userStore = useUserStore();
const dialogAsync = ref(false);
const uploadRef = ref();
const sysLastUpdateTime = ref();
const sysSerialnumber = ref();
const sysVersionNumber = ref();
const productName = JSON.parse(sessionStorage.getItem("productInfo")).productName;

onMounted(async () => {
  let { data: res } = await req_getSysLastUpdateTime();
  sysLastUpdateTime.value = moment(res.updatedAt).format("YYYY-MM-DD HH:mm:ss");
  let { data: res1 } = await req_getSysSerialnumber();
  sysSerialnumber.value = res1.serialNumber;
  let { data: res2 } = await req_getSystemVersionNumber();
  sysVersionNumber.value = res2;
});

const progressPercent = ref(0);
const uploadFileName = ref("");
const onSuccess = (file) => {
  if (file.status === "ready") {
    // 创建 FormData 对象
    let formData = new FormData();
    // 添加文件到 FormData 对象
    formData.append("file", file.raw);
    axios({
      method: "post",
      headers: {
        "Content-Type": "multipart/form-data",
        accesstoken: getToken(),
      },
      url: "/api/v2.0/files/console/uploadimage",
      data: formData,
      onUploadProgress: (progressEvent) => {
        progressPercent.value = Number(
          ((progressEvent.loaded / progressEvent.total) * 100).toFixed(0)
        );
      },
    })
      .then((res) => {
        if (res.status == 200 && res.data) {
          uploadFileName.value = file.name;
          ElMessage.success("上传成功");
        } else {
          uploadFileName.value = "";
          ElMessage.error("上传失败");
        }
      })
      .catch((err) => {
        uploadFileName.value = "";
        ElMessage.error("上传失败");
      });
  }
};
const closeDialog = () => {
  dialogAsync.value = false;
};
const updateStatus = ref("");
const timer = ref(null);
const handleUpdate = () => {
  updateStatus.value = "升级中";
  req_systemUpgrade()
    .then(async (res) => {
      if (res && !res.error) {
        updateStatus.value = "升级完成";
        timer.value = setInterval(() => {
          getDeviceInfo();
        }, 3000);
      } else {
        updateStatus.value = "升级失败";
      }
    })
    .catch((err) => {
      updateStatus.value = "升级失败";
    });
};
const getDeviceInfo = async () => {
  await req_getDeviceInfo();
};
onUnmounted(() => {
  clearInterval(timer.value);
});
</script>

<style lang="scss" scoped>
.upgrade {
  font-size: 16px;
  background-color: #fff;
  color: rgba(0, 0, 0, 0.65);
  border-radius: 6px;
  padding: 80px 0 30px 60px;
  :deep(.el-form-item__label){
    font-size: 16px;
    color: rgba(0, 0, 0, 0.65);
  }
  :deep(.el-form-item__content){
    font-size: 16px;
  }
  .browse-btn{
    color: rgba(0, 0, 0, 0.65);
  }
}
.logo-img {
  display: block;
  width: 280px;
  height: 76px;
}
.upload_content,
.upload-demo {
  display: flex;
  align-items: center;
}
:deep(.el-upload-list) {
  display: none;
}
:deep(.el-progress) {
  width: 300px;
  margin-left: 15px;
}
.dialog-header {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
}
.config-body {
  margin: 25px 20px;
}
.update-tips {
  font-size: 16px;
}
.dialog-footer {
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
}
</style>
